<?php


namespace app\admin\controller;


use app\admin\model\Admin;
use app\admin\validate\AdminValidate;
use app\AdminBaseController;
use think\captcha\facade\Captcha;
use think\exception\ValidateException;
use think\facade\Request;
use think\facade\Session;
use think\facade\View;

class login extends AdminBaseController
{
    //登录首页
    public function index(){
        return View::fetch('login');
    }

    //登录处理
    public function login(){
        //用户名
        $username = Request::param('username');
        //密码
        $password = Request::param('password');
        //验证码
        $verifyCode = Request::param('verifyCode');

        $data = [
            'username'=>$username,
            'password'=>$password,
            'verifyCode'=>$verifyCode
        ];

        //登录数据校验
        try {
            validate(AdminValidate::class)->scene('login')->check($data);
        }catch (ValidateException $exception){
            return $this->jsonApi($exception->getError(),'401');
        }

        //数据库账户密码校验
        $admin = Admin::where('username', $data['username'])->find();

        if (empty($admin)){
            return $this->jsonApi('用户名或密码错误','401');
        }

        //判断密码是否正确
        if (!strcmp($data['password'],$admin['password'])==0){
            return $this->jsonApi('用户名或密码错误','401');
        }

        //session存储用户数据
        Session::set('Admin_User',$admin);

        //后台首页菜单数据

        return $this->jsonApi('用户登录成功','200');
    }

    /**
     * 验证码
     */
    public function verify(){
        return Captcha::create();
    }



}